<?php

namespace App\Http\Model;

use App\Lib\Publisher;
use App\Lib\Snowflake\Snowflake;
use App\Lib\Snowflake\SnowflakeGenerator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class FinanceDiamond extends Base
{
    protected $table = 'finance_diamond_pay_rule';
    protected $streamTable = 'finance_diamond_stream';
    public $timestamps = false;
    private $redis_cache_finance_user_wallet = "CACHE:FINANCE:USER:WALLET";
    private $redis_last_stream_id = "FINANCE:LAST:STREAM:ID";
    private $redis_recharge_ratio = 'FINANCE:RECHARGE:RATIO';
    public $day_consume_limit = 40000; //每日消费钻石限制

    private $redis_user_red_envelope_day_send = 'FINANCE:USER:REDENVELOPE:DAY:SEND';

    CONST DIAMOND_TYPE_TRUTH_OR_DARE = 51; // 真心话大冒险

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    //钻石购买规则信息
    public function getDiamondRuleInfo($condition, $fields)
    {
        $document = DB::table($this->table)->where($condition)->orderBy('price', 'asc')->get($fields);

        $result = self::objToArray($document);
        foreach ($result as $key => $value) {
            $result[$key]['corner'] = !empty($value['corner']) ? build_image($value['corner'])  : $value['corner'];
        }
        return $result;
    }



    //获取充值规则
    public function getDiamondRule($rule_id)
    {
        $condition['rule_id'] = $rule_id;
        $fields = ['rule_id','price','diamond_amount','plat_type', 'apple_product_id', 'diamond_extra_num'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }

    //钻石购买规则查询 1苹果
    public function getDiamondRuleIos($rule_id)
    {
        $condition['rule_id'] = $rule_id;
        $condition['plat_type'] = 1;
        $fields = ['rule_id','price','diamond_amount','plat_type', 'apple_product_id'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }


    /**
     * 钻石购买规则查询 7：LLIOS
     * @param $rule_id
     * @return mixed
     */
    public function getDiamondRuleLLIos($rule_id)
    {
        $condition['rule_id'] = $rule_id;
        $condition['plat_type'] = 7;
        $fields = ['rule_id','price','diamond_amount','plat_type', 'apple_product_id'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }

    public function getDiamondRulePi($apple_product_id){
        $condition['apple_product_id'] = $apple_product_id;
        //$condition['plat_type'] = 1;
        $fields = ['rule_id','price','diamond_amount','plat_type', 'apple_product_id'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }

    //钻石购买规则查询 2安卓
    public function getDiamondRuleAndroid($rule_id)
    {
        $condition['rule_id'] = $rule_id;
        $condition['plat_type'] = 2;
        $fields = ['rule_id','price','diamond_amount','plat_type'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }

    /**
     * 钻石购买规则查询 3apple内购
     * @param $rule_id
     * @return mixed
     */
    public function getDiamondRuleApple($rule_id)
    {
        $condition['rule_id'] = $rule_id;
        $condition['plat_type'] = 3;
        $fields = ['rule_id','price','diamond_amount','plat_type'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }

    /**
     * 钻石购买规则查询 4公众号
     * @param $rule_id
     * @return mixed
     */
    public function getDiamondRuleMp($rule_id)
    {
        $condition['rule_id'] = $rule_id;
        $condition['plat_type'] = 4;
        $fields = ['rule_id','price','diamond_amount','plat_type'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }


    /**
     * 代充
     * @param $rule_id
     * @return mixed
     */
    public function getDiamondRuleAgent($rule_id)
    {
        $condition['rule_id'] = $rule_id;
        $condition['plat_type'] = 4;
        $fields = ['rule_id','price','diamond_amount','plat_type'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }


    /**
     * 钻石购买规则查询 6：IOS企业
     * @param $rule_id
     * @return mixed
     */
    public function getDiamondRuleEIOS($rule_id)
    {
        $condition['rule_id'] = $rule_id;
        $condition['plat_type'] = 6;
        $fields = ['rule_id','price','diamond_amount','plat_type'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }


    /**
     * 钻石购买规则查询 5：华为
     * @param $rule_id
     * @return mixed
     */
    public function getDiamondRuleHuawei($rule_id)
    {
        $condition['rule_id'] = $rule_id;
        $condition['plat_type'] = 5;
        $fields = ['rule_id','price','diamond_amount','plat_type'];
        $document = DB::table($this->table)->where($condition)->first($fields);
        $ret = self::objToArray($document);
        return $ret;
    }

    //钻石明细
    public function getDiamondListData($userId, $page, $page_size)
    {
        $condition = ['user_id' => $userId];
        $fields = ['diamond_type', 'pay_type', 'diamond_desc', 'diamond_value', 'change_timestamp', 'room_id'];
        $document = DB::table($this->streamTable)
            ->where($condition)
            ->orderBy('change_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);

        $result = self::objToArray($document);

        return $result;
    }



    /**
     * 钻石变更
     * @param int $user_id
     * @param int $from_user_id
     * @param int $room_id
     * @param int $diamond_type 0.礼物、1.守护、2.商品、 3.充值 4.后台钻石-加减、5.兑换金币、6、7：活动返现充值、8：钻石兑换金豆 9
     * 10.系统  11 发放红包 12.收红包 13.开箱子 17.背包礼物兑换 20：任务奖励 21:钻石代充 22:转盘奖券购买 23开启夺宝-支付钻石 24.参加夺宝-支付钻石
     * 25. 26.炼金 27.七夕滑动购买机会 28.七夕购买道具(荣耀戒指与卡片)29交公会押金 30 提取押金 31 解散公会退还押金32 瓜分活动返钻石
     * 33正数为福袋活动返钻石、负数为开消耗钻石 34 35元宵节拼手气报名 36元宵节拼手气瓜分 40一键完成每日任务 41补签 42阿来的福袋 43送祝福 44许愿池许愿
     * 45雇佣外星人 46开启贝阙珠宫 47开启瑶台银阙 48开启金玉满堂 49钻石兑换音符 50锦鲤奖金 60创建福袋 65打神兽活动购买道具 66蜜屋 70用户关系购买道具  82回归活动获得钻石
     * 
     * 0=购买送礼物 6=许愿池 71=缘分配对购买次数 100=购买金豆
     * 
     * @param int $diamond_value   [支出使用负数]
     * @param string $diamond_desc
     * @return bool
     */
    public function inc($user_id, $from_user_id, $room_id, $diamond_type, $diamond_value, $diamond_desc){
        if(empty($user_id)) {
            return false;
        }
        $incrRet = DB::table("finance_wallet")
            ->where(['user_id'=>$user_id])
            ->increment('diamond_balance',$diamond_value,['change_timestamp'=>time()]);

        $wallet = DB::table('finance_wallet')
            ->where('user_id', '=', $user_id)
            ->first(['diamond_balance']);

        //增加一个track_id; add by zxiaofee
        // $trackId = SnowflakeGenerator::generateId('finance_diamond_stream');
        // 参数
        $diamondParams = [
            // "track_id" => $trackId,
            "user_id" => $user_id,
            "room_id" => $room_id,
            "diamond_value" => $diamond_value,
            "from_user_id" => $from_user_id,
            "diamond_type" => $diamond_type,
            "diamond_desc" => $diamond_desc,
            "diamond_balance" => $wallet->diamond_balance,
            "change_timestamp" => time()
        ];

        $insertRet = DB::table("finance_diamond_stream")->insert($diamondParams);
        Redis::DEL($this->redis_cache_finance_user_wallet .':'. $user_id);

        return true;
    }




    /**统计钻石流水
     * @return mixed
     */
    public function statisticsEveryDayDiamondStream(){
        $last_stream_id = Redis::get($this->redis_last_stream_id) ?? 0;
        $fields = ['stream_id','room_id', 'user_id', 'diamond_value', 'change_timestamp'];
        $document = DB::table($this->streamTable)
            ->where('stream_id','>' ,$last_stream_id)
            ->where('room_id', '>', 0)
            ->where('diamond_value' ,'<' ,0)
            ->orderBy('stream_id' ,'asc')
            ->get($fields);
        $result = self::objToArray($document);
        if(!empty($result)){
            Redis::set($this->redis_last_stream_id ,$result[count($result)-1]['stream_id']);
        }
        return $result;
    }

    /**根据用户uid统计砖石流水
     * @return mixed
     */
    public function statisticsEveryDayDiamondByUid($user_ids){
        $user_ids = empty($user_ids) ? [] : $user_ids;
        $fields = ['stream_id','room_id', 'user_id', 'diamond_value', 'change_timestamp'];
        $document = DB::table($this->streamTable)
            ->whereNotIn('user_id' ,$user_ids)
            ->where('change_timestamp' ,'>=',strtotime(date('Y-m-d')))
            ->where('change_timestamp' ,'<',strtotime(date('Y-m-d',strtotime('+1 day'))))
            ->where('room_id', '>', 0)
            ->where('diamond_value' ,'<' ,0)
            ->orderBy('change_timestamp','asc')
            ->get($fields);
        $result = self::objToArray($document);
        return $result;
    }

    /**获取自定义充值钻石的比例
     * @return mixed
     */
    public function getRechargeRatio(){
        return Redis::get($this->redis_recharge_ratio) ?? 100;
    }

    /**获取用户当日消费钻石数
     * @param $userId
     * @param int $startTime
     * @param int $endTime
     * @return float|int
     */
    public function getUserDayConsume($userId ,$startTime = 0 ,$endTime = 0){
        $startTime = empty($startTime) ? strtotime(date('Y-m-d')) : $startTime;
        $endTime = empty($endTime) ? time() : $endTime;
        $condition['user_id'] = $userId;
        $sum = DB::table($this->streamTable)
            ->where('user_id',$userId)
            ->where('change_timestamp', '>', $startTime)
            ->where('change_timestamp', '<', $endTime)
            ->where('diamond_value','<',0)
            ->where('diamond_type' ,'!=' ,2)
            ->sum('diamond_value');
        return empty($sum) ? 0 : abs($sum);
    }

    /**获取用户24小时消费钻石数
     * @param $userId
     * @return int
     */
    public function getUserConsume24($userId) : int{
        $startTime = strtotime(date('Y-m-d'));
        $endTime =  time();
        $sum = DB::table($this->streamTable)
            ->where('user_id',$userId)
            ->where('change_timestamp', '>', $startTime)
            ->where('change_timestamp', '<', $endTime)
            ->where('diamond_value','<',0)
            ->where('diamond_type' ,'!=' ,2)
            ->sum('diamond_value');
        return empty($sum) ? 0 : abs($sum);
    }

    public function addRedEnvelopeDaySendCount(int $userId, int $count){
        $key = $this->redis_user_red_envelope_day_send . ":" . date("Y-m-d") . ":" . $userId;
        if (Redis::exists($key)) {
            return Redis::incrby($key, $count);
        }
        return Redis::set($key, $count, 'Ex', 3600 * 24 + 360);
    }
    public function getRedEnvelopeDaySendCount(int $userId){
        $key = $this->redis_user_red_envelope_day_send . ":" . date("Y-m-d") . ":" . $userId;
        return Redis::get($key);
    }
}
